package util;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.hazelcast.core.EntryEvent;
import com.hazelcast.core.IMap;
import com.hazelcast.map.listener.EntryAddedListener;
import com.hazelcast.map.listener.EntryRemovedListener;
import com.hazelcast.map.listener.EntryUpdatedListener;

@Service
public class MapService {
	private final static Logger logger = LoggerFactory.getLogger(MapService.class);

	@Resource(name = NearCacheTest.MAP)
	public IMap<String, String> testmap;

	@PostConstruct
	public void init() {
		testmap.addEntryListener(new MyEntryListener(), true);
	}

	@Cacheable(NearCacheTest.MAP)
	public String read(String key) {
		logger.info("==========remote read");
		return testmap.get(key);
	}

	@CacheEvict(NearCacheTest.MAP)
	public void evict(String key) {

	}

	private class MyEntryListener implements EntryAddedListener<String, String>, EntryRemovedListener<String, String>,
			EntryUpdatedListener<String, String> {
		@Override
		public void entryAdded(EntryEvent<String, String> event) {
			logger.info("entryAdded: " + event);
			// evict(event.getKey());
		}

		@Override
		public void entryRemoved(EntryEvent<String, String> event) {
			logger.info("entryRemoved: " + event);
			// evict(event.getKey());
		}

		@Override
		public void entryUpdated(EntryEvent<String, String> event) {
			logger.info("entryUpdated: " + event);
			// evict(event.getKey());
		}
	}
}